package com.mock.water.config.shiro;

import com.mock.water.core.utils.JwtUtils;
import com.mock.water.modules.system.user.entity.UserEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * $$ shiro的执行流程： preHandle -> isAccessAllowed -> isLoginAttempt -> executeLogin
 *
 * @author ifredomvip@gmail.com
 * @version 1.0.0
 * @date 2022/10/27 17:18
 **/
@Slf4j
public class MyAuthFilter extends BasicHttpAuthenticationFilter {

    private static final String TOKEN = "Authorization";

    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
        //获取请求token
        String token = getRequestToken((HttpServletRequest) request);

        if (StringUtils.isBlank(token)) {
            return null;
        }

        return new JwtToken(token);
    }

    /**
     * 第一步
     * 前置拦截处理
     *
     * @param request  请求
     * @param response 响应
     * @return boolean
     * @throws Exception 异常
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        log.info("preHandle - 周期");
        return super.preHandle(request, response);
    }

    /**
     * 第二步
     * 所有请求都会进入该方法
     * 1. 返回true，则允许访问该url。不会执行 onAccessDenied 方法
     * 2. 返回false，则会继续执行 onAccessDenied 方法，并根据 onAccessDenied 返回值决定是否允许访问url
     *
     * @param request     请求
     * @param response    响应
     * @param mappedValue 映射值
     * @return boolean
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        log.info("允许访问 - 周期");
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        // 过滤options方法。跨域时会首先发送一个option请求
        if (((HttpServletRequest) request).getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpResponse.setStatus(HttpStatus.OK.value());
            log.info("拦截option");
            return true;
        }

        fillCorsHeader(httpRequest, httpResponse);

        // 所有自定义过滤器得请求都需要携带token
        return false;
    }

    /**
     * 第三步
     * isAccessAllowed()方法返回false,会进入该方法，表示拒绝访问
     * 所有过滤器处理请求都可以在 isAccessAllowed中处理，或者在 onAccessDenied 中处理
     * 由于过滤器在controller前运行，token过期时，抛出的异常不会全局异常捕获，而在 onAccessDenied 是可以精准抛出此异常。
     * 所以在 onAccessDenied 中处理
     *
     * @param request  请求
     * @param response 响应
     * @return boolean
     * @throws Exception 异常
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        log.info("拒绝访问 - 周期");
        String token = getRequestToken((HttpServletRequest) request);

        if (StringUtils.isBlank(token)) {
            saveRequestAndRedirectToLogin(request, response);
            return false;
        }

        String username = JwtUtils.getUserName(token);

        boolean verify = JwtUtils.verify(token, username, JwtUtils.secret);

        if (!verify) {
            log.info("token有问题");
            return false;
        }

        return true;
    }

    /**
     * 获取请求的token
     */
    private String getRequestToken(HttpServletRequest httpRequest) {
        // 从header中获取token
        String token = httpRequest.getHeader(TOKEN);
        // 如果header中不存在token，则从参数中获取token
        if (StringUtils.isBlank(token)) {
            token = httpRequest.getParameter(TOKEN);
        }
        String bearer = token;

        if (token != null) {
            // 去掉前缀
            bearer = token.split("Bearer")[1].trim();
        }

        return bearer;
    }

    /**
     * 跨域请求的解决方案之一
     *
     * @param request  请求
     * @param response 响应
     */
    protected void fillCorsHeader(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html;charset=UTF-8");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        response.setHeader(
                "Access-Control-Allow-Headers",
                request.getHeader("Access-Control-Request-Headers")
        );
    }
}
